package com.dynamicthreadpool.spi.support;

import com.dynamicthreadpool.spi.DynamicThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 命名线程工厂实现，用于创建带有自定义名称的线程
 */
public class NamedThreadFactoryImpl implements DynamicThreadFactory {

    private static final AtomicInteger POOL_SEQ = new AtomicInteger(1);

    private final AtomicInteger threadNum = new AtomicInteger(1);
    private String prefix;
    private boolean daemon = false;
    private final java.lang.ThreadGroup group;

    public NamedThreadFactoryImpl() {
        this("pool-" + POOL_SEQ.getAndIncrement(), false);
    }

    public NamedThreadFactoryImpl(String prefix) {
        this(prefix, false);
    }

    public NamedThreadFactoryImpl(String prefix, boolean daemon) {
        this.prefix = prefix + "-thread-";
        this.daemon = daemon;
        SecurityManager s = System.getSecurityManager();
        this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
    }

    @Override
    public java.lang.Thread newThread(Runnable r) {
        String name = prefix + threadNum.getAndIncrement();
        Thread ret = new Thread(group, r, name, 0);
        ret.setDaemon(daemon);
        return ret;
    }

    @Override
    public DynamicThreadFactory setName(String name) {
        if (name != null && !name.isEmpty()) {
            this.prefix = name + "-thread-";
        }
        return this;
    }

    @Override
    public DynamicThreadFactory setDaemon(boolean daemon) {
        this.daemon = daemon;
        return this;
    }

    @Override
    public String getName() {
        return prefix.substring(0, prefix.length() - "-thread-".length());
    }

    public java.lang.ThreadGroup getThreadGroup() {
        return group;
    }
}